package com.fanqi.nxplayer.ipc;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.fanqi.ipcapp.Book;
import com.fanqi.ipcapp.IBookManager;
import com.fanqi.nxplayer.R;

import java.util.List;

public class IpcActivity extends AppCompatActivity {

    private Button add;
    private TextView libTv;

    private StringBuilder sb = new StringBuilder();
    private IBookManager bookManager;
    private boolean isConnected = false;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isConnected = true;
            bookManager = IBookManager.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isConnected = false;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipc);

        add = findViewById(R.id.add);
        libTv = findViewById(R.id.book_list);

        Intent intent = new Intent();
        intent.setAction("com.fanqi.ipc.TwoAppIPCService");
        intent.setPackage("com.fanqi.ipcapp");
        //开启服务
        bindService(intent, connection, BIND_AUTO_CREATE);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Book book = new Book("no" + System.currentTimeMillis(), "Android高级开发");
                if (isConnected && bookManager != null) {
                    try {
                        bookManager.addBook(book);
                        updateLibTv();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    private void updateLibTv() {
        if (isConnected && bookManager != null) {
            try {
                List<Book> bookList = bookManager.getBooks();
                for (int i = 0; i < bookList.size(); i++) {
                    sb.append(bookList.get(i).getNo() + "书名：" + bookList.get(i).getName());
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        libTv.setText("");
        libTv.setText(sb.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
